import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("./draco/");
const loadManager = new GLTFLoader().setDRACOLoader(dracoLoader)
/**
     * 创建园区附加的环境组件，树
     * @param data 
     */
export async function applyEnvironment(data, scene) {
    // @ts-ignore
    await Promise.all((data.data || []).map(async (cur) => {
        await createEnvironment(cur, scene)
    }))
}

export async function createEnvironment(data, scene) {
    const { path, pos } = data || {}
    const array = [];
    const dummy = new THREE.Object3D();
    await Promise.all((path || []).map(async ({ url, scale }) => {
        const obj = await new Promise((resolve, reject) => {
            try {
                loadManager.load(url, function (model) {
                    resolve(model.scene)
                }, undefined, function (error) {

                    reject(new THREE.Object3D())
                    console.error('---------模型加载异常', error, url)
                })
            } catch (error) {
                reject(new THREE.Object3D())
                console.error('---------异常模型数据', url)
            }
        });
        // 材质集合
        const mats = [];
        obj.traverse((ch) => {
            if (ch instanceof THREE.Mesh) {
                // ch.material.side = 2;
                // 动态更新材质
                const mesh = new THREE.InstancedMesh(ch.geometry, ch.material, pos.length);
                // @ts-ignore 添加私有属性
                // mesh._applyTheme('default','Device');
                mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
                mesh.renderOrder = 2;
                mats.push(mesh);
                scene.add(mesh);

                // mesh.scale.set(0.5,0.5,0.5)
                // mesh.receiveShadow = true;
                mesh.castShadow = true;
            }
        })
        // 模型拆解成instance 对象
        array.push({
            mats,
            scale
        })
    }))

    const updateMesh = (ch = [], i) => {
        ch.forEach((mesh) => {
            mesh.setMatrixAt(i, dummy.matrix);
        })
    }

    //动态创建所有的instace对象
    for (let i = 0; i < pos.length;) {
        // @ts-ignore
        const { mats, scale = [1, 1, 1] } = array[Math.ceil(Math.random() * path.length) - 1]
        dummy.position.set(pos[i][0], pos[i][1], pos[i][2]);
        dummy.scale.set(scale[0], scale[1], scale[2]);
        dummy.updateMatrix();
        updateMesh(mats, i++)

    }

}

export function updateCssStatus(bool) {
    const headerTitle = document.getElementById('header-title');
    const headerSmTitle = document.getElementById('header-sm-title');
    const wrapperPageError = document.getElementById('wrapper-page-error');
    const footerError = document.getElementById('footer-error');
    if (wrapperPageError && headerSmTitle && headerTitle) {
        if (!bool) { // 恢复默认状态
            headerTitle.classList.add('hader-title-error')
            headerSmTitle.classList.add('sm-title-error')
            wrapperPageError.classList.add('wrapper-page-error');
            footerError.classList.add('footer-bg-error')
        } else { // 告警状态
            headerTitle.classList.remove('hader-title-error')
            headerSmTitle.classList.remove('sm-title-error')
            wrapperPageError.classList.remove('wrapper-page-error')
            footerError.classList.remove('footer-bg-error')
        }
    }
}

export function getAlarmTagConfig(config) {

    let html = `<div class="alarm-wrapper">
        <div class="normal-bg">
        <div class="boy">
            <img src="${config.type === 1 ? "./tags/boy.png" : "../tags/girl.png"}" />
        </div>`

    html += `<div class="content">`
            
    for(let cur in config.values){
        html+=`<div>${cur}：${config.values[cur]}</div>`
    }    

    html += `</div></div>
        <div class="handle">立即处理</div>
    </div>`

    return html;
}